<?php


$wechat = new Wechat();
//验证工作只需一次
//$wechat->valid();
$wechat->responseMsg();

class Wechat
{
	public function responseMsg()
	{
		if (PHP_VERSION >= 7) {
			//PHP7.0以上版本使用此方式获取数据
			$postStr = file_get_contents('php://input');
		} else {
			//PHP7.0以下版本使用此方式获取数据
			$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		}
		//file_put_contents('2.txt', $postStr);
		//解析XML
		$xml = simplexml_load_string($postStr);
		//file_put_contents('3.txt', $xml->Content);
		
		$responseXml = '<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[%s]]></Content>
						</xml>';
		$content = '你好，你是不是很无聊';
		if (mb_stristr($xml->Content,'浩哥')) {
			$content = '帅呆了^_^';
		} else if (mb_stristr($xml->Content,'杰哥')) {
			$content = '帅是困扰杰哥多年的问题';
		}
		$responseXml = sprintf($responseXml,$xml->FromUserName,$xml->ToUserName,time(),$content);
		
		echo $responseXml;
	}

	public function valid()
	{
		$echoStr = $_GET['echostr'];
		if ($this->checkSignature()) {
			echo $echoStr;
		}
		exit;
	}

	private function checkSignature()
	{
		$signature = $_GET['signature'];
		$timestamp = $_GET['timestamp'];
		$nonce = $_GET['nonce'];
		$echoStr = $_GET['echostr'];
		$token = 'tornado';

		$arr = [$timestamp,$nonce,$token];
		sort($arr, SORT_STRING);
		$str = join($arr);
		$str = sha1($str);

		if ($str == $signature) {
			return true;
		} 
		return false;
	}
}